<template>
  <div id="review">
    <el-container style="height: 100vh; border: 1px">
      <!-- 头部信息 -->
      <el-header>
        <HeaderBar></HeaderBar>
      </el-header>
      <el-container style="flex: 1; display: flex;">
        <!-- 左侧栏 -->
        <el-aside :width="sidebarWidth" style="transition: width 0.3s ease;">
          <Sidebar @sidebar-toggle="handleSidebarToggle"></Sidebar>
        </el-aside>
        <!-- 主体内容区 -->
        <el-main :style="{
          marginLeft: '0',
          transition: 'margin-left 0.3s ease',
          width: `calc(100% - ${sidebarWidth})`
        }">
          <!-- 选项卡切换 -->
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="职位审核" name="job"></el-tab-pane>
            <el-tab-pane label="公司审核" name="company"></el-tab-pane>
          </el-tabs>

          <!-- 搜索区域 -->
          <el-row class="search">
            <input class="relative" v-model="searchKeyword" type="text" placeholder="搜索...">
            <el-select v-if="activeTab === 'job'" v-model="selectedAuditType" placeholder="审核类型" clearable>
              <el-option value="all" label="全部"></el-option>
              <el-option value="review" label="待审核"></el-option>
              <el-option value="change" label="待变更"></el-option>
            </el-select>
          </el-row>

          <!-- 职位表格（同时展示审核和变更数据） -->
          <el-table v-if="activeTab === 'job'" :data="paginatedTableData" class="audit-table" style="width: 100%">
            <el-table-column prop="positionName" label="职位名称" width="200"></el-table-column>
            <el-table-column prop="name" label="发布方" width="200"></el-table-column>
            <el-table-column label="月薪" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.lowestSalaryMonth }}-{{ scope.row.highestSalaryMonth }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="150">
              <template slot-scope="scope">
                <span class="status-badge" :class="getStatusClass(scope.row.status)">{{
                  getStatusText(scope.row.status) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="endAt" label="结束时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.endAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button size="mini" type="info" icon="el-icon-view"
                  @click="viewDetails(scope.row, scope.row.isChange)">
                  审核
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 公司表格 -->
          <el-table v-if="activeTab === 'company'" :data="paginatedTableData" class="audit-table" style="width: 100%">
            <el-table-column prop="name" label="公司名称" width="200"></el-table-column>
            <el-table-column prop="userName" label="负责人" width="180"></el-table-column>
            <el-table-column prop="companyIndustry" label="公司类型" width="180"></el-table-column>
            <el-table-column prop="createDate" label="注册时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createDate) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button size="mini" type="info" icon="el-icon-view" @click="viewDetails(scope.row, false)">
                  审核
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[5, 10, 20]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="filteredTableData.length">
          </el-pagination>

          <!-- 审核详情弹窗 -->
          <el-dialog :title="isChange ? '职位变更审核' : '职位审核'" :visible.sync="dialogVisible" width="70%">
            <div class="audit-detail-container">
              <!-- 职位变更弹窗 -->
              <div v-if="isChange && activeTab === 'job'" class="detail-content">
                <h3>{{ currentItem.newPositionMessage.positionName || '职位名称' }}</h3>

                <!-- 变更数据对比表格 -->
                <div class="change-compare-table">
                  <div class="compare-header">
                    <div class="compare-label">字段</div>
                    <div class="compare-old">原始数据</div>
                    <div class="compare-new">变更后数据</div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">发布方</div>
                    <div class="compare-old">{{ currentItem.oldPositionMessage.name || '-' }}</div>
                    <div class="compare-new">{{ currentItem.newPositionMessage.name || '-' }}</div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">工作类型</div>
                    <div class="compare-old">{{ currentItem.oldPositionMessage.positionType || '-' }}</div>
                    <div class="compare-new">{{ currentItem.newPositionMessage.positionType || '-' }}</div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">月薪</div>
                    <div class="compare-old">
                      {{ formatSalary(currentItem.oldPositionMessage.lowestSalaryMonth,
                        currentItem.oldPositionMessage.highestSalaryMonth) }}
                    </div>
                    <div class="compare-new">
                      {{ formatSalary(currentItem.newPositionMessage.lowestSalaryMonth,
                        currentItem.newPositionMessage.highestSalaryMonth) }}
                    </div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">学历要求</div>
                    <div class="compare-old">{{ getEducationTypeClass(currentItem.oldPositionMessage.education) }}</div>
                    <div class="compare-new">{{ getEducationTypeClass(currentItem.newPositionMessage.education) }}</div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">职位描述</div>
                    <div class="compare-old">{{ currentItem.oldPositionMessage.positionDetail || '-' }}</div>
                    <div class="compare-new">{{ currentItem.newPositionMessage.positionDetail || '-' }}</div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">职位要求</div>
                    <div class="compare-old">{{ currentItem.oldPositionMessage.positionRequire || '-' }}</div>
                    <div class="compare-new">{{ currentItem.newPositionMessage.positionRequire || '-' }}</div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">开始时间</div>
                    <div class="compare-old">{{ formatDate(currentItem.oldPositionMessage.startAt) }}</div>
                    <div class="compare-new">{{ formatDate(currentItem.newPositionMessage.startAt) }}</div>
                  </div>

                  <div class="compare-row">
                    <div class="compare-label">结束时间</div>
                    <div class="compare-old">{{ formatDate(currentItem.oldPositionMessage.endAt) }}</div>
                    <div class="compare-new">{{ formatDate(currentItem.newPositionMessage.endAt) }}</div>
                  </div>
                </div>
              </div>

              <!-- 职位审核弹窗 -->
              <div v-if="!isChange && activeTab === 'job'" class="detail-content">
                <h3>{{ currentItem.positionName || '职位名称' }}</h3>
                <div class="detail-row">
                  <span class="label">发布方：</span>
                  <span>{{ currentItem.name || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">工作类型：</span>
                  <span>{{ currentItem.positionType || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">月薪：</span>
                  <span>{{ formatSalary(currentItem.lowestSalaryMonth, currentItem.highestSalaryMonth) || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">学历要求：</span>
                  <span>{{ getEducationTypeClass(currentItem.education) || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">职位描述：</span>
                  <p>{{ currentItem.positionDetail || '-' }}</p>
                </div>
                <div class="detail-row">
                  <span class="label">职位要求：</span>
                  <p>{{ currentItem.positionRequire || '-' }}</p>
                </div>
                <div class="detail-row">
                  <span class="label">开始时间：</span>
                  <p>{{ formatDate(currentItem.startAt) || '-' }}</p>
                </div>
                <div class="detail-row">
                  <span class="label">结束时间：</span>
                  <p>{{ formatDate(currentItem.endAt) || '-' }}</p>
                </div>
                <div class="detail-row">
                  <span class="label">状态：</span>
                  <span class="status-badge" :class="getStatusClass(currentItem.status)">{{
                    getStatusText(currentItem.status) }}</span>
                </div>
              </div>

              <!-- 公司审核弹窗 -->
              <div v-if="activeTab === 'company'" class="detail-content">
                <h3>{{ currentItem.name || '公司名称' }}</h3>
                <div class="detail-row">
                  <span class="label">负责人：</span>
                  <span>{{ currentItem.userName || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">公司类型：</span>
                  <span>{{ currentItem.companyIndustry || '-' }}</span>
                </div>
              </div>

              <!-- 审核意见 -->
              <div class="audit-comment">
                <el-form>
                  <el-form-item label="审核意见">
                    <el-input type="textarea" v-model="comment" :rows="4" placeholder="请输入审核意见"></el-input>
                  </el-form-item>
                </el-form>
              </div>
            </div>

            <!-- 审核操作按钮 -->
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmApprove(currentItem)">通过</el-button>
              <el-button type="danger" @click="confirmReject(currentItem)">拒绝</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import Sidebar from "@/components/ManagerSidebar.vue";
import HeaderBar from "@/components/ManagerHeaderBar.vue";
import {
  getRecruiterCompanyRegisterLists,
  verifyUserCompanyRegister,
  verifyUserCompanyRegisterFailed,
} from "@/util/manager_api/company";
import {
  getPublishPositionLists,
  verifyPublishPosition,
  verifyPublishPositionFailed,
  getUpdatedPositionLists,
  VerifyChangePosition,
  VerifyChangePositionFailed
} from "@/util/manager_api/position";

export default {
  components: {
    Sidebar,
    HeaderBar
  },
  data() {
    return {
      activeTab: 'job',
      searchKeyword: '',
      selectedAuditType: 'all',
      companyData: [],
      jobReviewData: [], // 普通职位审核数据
      jobChangeData: [], // 职位变更原始数据（包含old和new）
      dialogVisible: false,
      currentItem: {}, // 当前操作的项
      comment: '',
      isSidebarCollapsed: false,
      isChange: false, // 标记当前弹窗是否为变更审核
      STATUS_ENUM: {
        REVIEWING: 1,   // 待审核（普通职位）
        CHANGING: 2,    // 待变更（职位变更）
      },
      currentPage: 1,
      pageSize: 5
    };
  },
  computed: {
    // 合并普通审核和变更数据，统一展示在表格
    filteredTableData() {
      let allData = [];

      if (this.activeTab === 'job') {
        const reviewData = this.jobReviewData.map(item => ({
          ...item,
          status: this.STATUS_ENUM.REVIEWING,
          isChange: false
        }));

        const changeData = this.jobChangeData.map(item => ({
          ...item.oldPositionMessage,
          status: this.STATUS_ENUM.CHANGING,
          isChange: true,
          original: item
        }));

        // 合并两类数据
        allData = [...reviewData, ...changeData];
      } else if (this.activeTab === 'company') {
        allData = this.companyData;
      }

      // 搜索过滤
      if (this.searchKeyword) {
        allData = allData.filter(item => {
          return Object.values(item).some(value => {
            return typeof value === 'string' && value.includes(this.searchKeyword);
          });
        });
      }
      if (this.activeTab === 'job' && this.selectedAuditType !== 'all') {
        allData = allData.filter(item => {
          if (this.selectedAuditType === 'review') {
            return !item.isChange; // 只显示普通审核
          } else {
            return item.isChange; // 只显示变更审核
          }
        });
      }
      if (this.activeTab === 'job') {
        allData.sort((a, b) => b.endAt - a.endAt);
      } else if (this.activeTab === 'company') {
        allData.sort((a, b) => b.createDate - a.createDate);
      }
      return allData;
    },
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredTableData.slice(start, end);
    },
    sidebarWidth() {
      return this.isSidebarCollapsed ? '30px' : '200px';
    }
  },
  created() {
    this.loadAuditData();
  },
  methods: {
    // 加载审核数据
    async loadAuditData() {
      const tab = this.$route.params.activeTab;
      if (tab) this.activeTab = tab;

      try {
        if (this.activeTab === 'job') {
          // 加载普通职位审核数据
          const reviewRes = await getPublishPositionLists();
          this.jobReviewData = reviewRes.data.data || [];

          // 加载职位变更数据
          const changeRes = await getUpdatedPositionLists();
          this.jobChangeData = changeRes.data.data || [];
        } else {
          // 加载公司审核数据
          const companyRes = await getRecruiterCompanyRegisterLists();
          this.companyData = companyRes.data.data || [];
        }
      } catch (error) {
        console.error("加载数据失败:", error);
        this.$message.error("加载数据失败，请重试");
      }
    },

    // 查看详情
    viewDetails(item, isChange) {
      this.isChange = isChange;
      // 变更数据需要取原始完整对象
      this.currentItem = isChange ? item.original : item;
      this.dialogVisible = true;
      this.comment = ''; // 重置审核意见
    },

    // 审核通过
    async confirmApprove(item) {
      try {
        let response;
        if (this.activeTab === 'job') {
          if (this.isChange) {
            // 职位变更通过      
            const positionId = item.oldPositionMessage.positionId;
            response = await VerifyChangePosition(positionId);
            this.$store.commit('manager/SET_TOKEN', response.data.data);
          } else {
            // 普通职位审核通过
            response = await verifyPublishPosition(item.code);
            this.$store.commit('manager/SET_TOKEN', response.data.data);
          }
        } else {
          // 公司审核通过
          response = await verifyUserCompanyRegister(item.phoneAes);
          this.$store.commit('manager/SET_TOKEN', response.data.data);
        }
        this.dialogVisible = false;
        this.loadAuditData(); // 重新加载数据
        this.$message.success("审核通过");
      } catch (error) {
        console.error("审核通过失败:", error);
        this.$message.error("操作失败，请重试");
      }
    },

    // 审核拒绝
    async confirmReject(item) {
      if (!this.comment) {
        this.$message.warning("请输入审核意见");
        return;
      }
      try {
        let response;
        if (this.activeTab === 'job') {
          if (this.isChange) {
            // 职位变更拒绝
            const positionId = item.oldPositionMessage.positionId
            response = await VerifyChangePositionFailed(positionId, this.comment);
            this.$store.commit('manager/SET_TOKEN', response.data.data);
          } else {
            // 普通职位审核拒绝
            response = await verifyPublishPositionFailed(item.code, this.comment);
            this.$store.commit('manager/SET_TOKEN', response.data.data);
          }
        } else {
          // 公司审核拒绝
          response = await verifyUserCompanyRegisterFailed(item.phoneAes, this.comment);
          this.$store.commit('manager/SET_TOKEN', response.data.data);
        }
        this.dialogVisible = false;
        this.comment = '';
        this.loadAuditData(); // 重新加载数据
        this.$message.success("已拒绝");
      } catch (error) {
        console.error("审核拒绝失败:", error);
        console.log('后端错误详情:', error.response?.data);
        this.$message.error("操作失败，请重试");
      }
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleDateString() + ' ' + date.toTimeString().substr(0, 5);
    },

    // 格式化月薪显示
    formatSalary(lowest, highest) {
      if (!lowest && !highest) return '';
      if (!highest) return `${lowest}K`;
      if (!lowest) return `${highest}K`;
      return `${lowest}-${highest}K`;
    },

    // 学历类型映射
    getEducationTypeClass(type) {
      const map = {
        'UNDERGRADUATE': '本科',
        'COLLEGE': '大专',
        'MASTER': '硕士',
        'DOCTOR': '博士',
        'OTHER': '其他'
      };
      return map[type] || '未说明';
    },

    // 获取状态类名
    getStatusClass(status) {
      switch (status) {
        case this.STATUS_ENUM.REVIEWING:
          return 'status-pending'; // 待审核 - 黄色
        case this.STATUS_ENUM.CHANGING:
          return 'status-changing'; // 待变更 - 绿色
        default:
          return '';
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case this.STATUS_ENUM.REVIEWING:
          return '待审核';
        case this.STATUS_ENUM.CHANGING:
          return '待变更';
        default:
          return '';
      }
    },

    // 侧边栏切换
    handleSidebarToggle(isCollapsed) {
      this.isSidebarCollapsed = isCollapsed;
    },

    // 处理选项卡切换
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.searchKeyword = '';
      this.selectedStatus = 'all';
      this.loadAuditData();
    },
    // 处理每页显示数量变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },

    // 处理当前页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    }
  }
};
</script>
<style scoped>
@import url('./ManaReviewView.css');
</style>